﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QuanLyTruongHoc_App.MyDataSet;
using QuanLyTruongHoc_App.MyDataSet.QLTHTableAdapters;

namespace QuanLyTruongHoc_App
{
    public partial class PhanQuyen : Form
    {
        public static readonly String[] HINH_THUC = new String[]
                                             { "Xem", 
                                               "Thêm mới", 
                                               "Sửa", 
                                               "Xóa" };

        private DataGridViewTextBoxColumn grc_TenQuyen;
        private DataGridViewCheckBoxColumn[] grc_quyen; // Them Moi, Xem, Sua, Xoa
        private DataTable data;
        private BindingSource binding = new BindingSource();
        private Boolean wasSave;

        private int idUser;

        public PhanQuyen()
        {
            InitializeComponent();
        }

        private void QLHinhThucCanBo_Load(object sender, EventArgs e)
        {
            refreshData();
        }

        private void checkUserPower()
        {
            int pow = PublicLib.getUserPower(PConst.QUYEN_PHAN_QUYEN);
            // user co quyen view
            tscb_User.Enabled = ((pow & PConst.POW_VIEW) > 0);
            // user co quyen them
            tsb_TaoMoi.Enabled = ((pow & PConst.POW_ADD) > 0);
            // user co quyen edit
            tsb_Luu.Enabled = ((pow & PConst.POW_EDIT) > 0);
            for (int i=0; i<grc_quyen.Length; i++)
                dg_DanhSach.Columns[dg_DanhSach.ColumnCount - i - 1].ReadOnly = !((pow & PConst.POW_EDIT) > 0);
            // user co delete
            tsb_Delete.Enabled = ((pow & PConst.POW_DEL) > 0);
        }

        private void loadComboBox()
        {
            int select = -1;
            wasSave = true;

            tbl_UserTableAdapter userAdap = new tbl_UserTableAdapter();
            userAdap.Connection.ConnectionString = PublicLib.getStrConn();
            userAdap.FillByFlag(qLTH.tbl_User, PConst.FLAG_NONE);

            for (int i = 0; i < qLTH.tbl_User.Rows.Count; i++)
            {
                tscb_User.Items.Add(qLTH.tbl_User.Rows[i][qLTH.tbl_User.unameColumn].ToString());
                if (qLTH.tbl_User.Rows[i][qLTH.tbl_User.unameColumn].ToString() == PublicLib.CURR_USER)
                    select = i;
            }

            // load cac loai quyen
            //binding = new BindingSource(new System.ComponentModel.Container());
            
            data = new DataTable();
            data.Columns.Add("ten", Type.GetType("System.String"));
            data.Columns.Add("xem", Type.GetType("System.Boolean"));
            data.Columns.Add("them", Type.GetType("System.Boolean"));
            data.Columns.Add("sua", Type.GetType("System.Boolean"));
            data.Columns.Add("xoa", Type.GetType("System.Boolean"));

            dg_DanhSach.DataSource = binding;
            //dg_DanhSach.DataBindings.Add("data", binding, "data");

            grc_TenQuyen = new DataGridViewTextBoxColumn();
            grc_TenQuyen.HeaderText = "Quyền";
            grc_TenQuyen.DataPropertyName = "ten";
            grc_TenQuyen.ReadOnly = true;

            dg_DanhSach.Columns.Add(grc_TenQuyen);

            grc_quyen = new DataGridViewCheckBoxColumn[HINH_THUC.Length];
            for (int i = 0; i < HINH_THUC.Length; i++)
            {
                grc_quyen[i] = new DataGridViewCheckBoxColumn();
                grc_quyen[i].HeaderText = HINH_THUC[i];
                grc_quyen[i].DataPropertyName = data.Columns[i + 1].ColumnName;
                dg_DanhSach.Columns.Add(grc_quyen[i]);
            }

            binding.DataSource = data;
            //dg_DanhSach.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dg_DanhSach_DataBindingComplete);

            sys_QuyenTableAdapter qAdap = new sys_QuyenTableAdapter();
            qAdap.Connection.ConnectionString = PublicLib.getStrConn();
            qAdap.Fill(qLTH.sys_Quyen);
            data.Rows.Clear();

            for (int i = 0; i < qLTH.sys_Quyen.Rows.Count; i++)
            {
                data.Rows.Add(qLTH.sys_Quyen.Rows[i][qLTH.sys_Quyen.QuyenColumn].ToString());
            }

            // set select user
            if (select != -1)
            {
                tscb_User.SelectedIndex = select;
            }
        }

        private void fillData()
        {
            if (tscb_User.SelectedIndex == -1) return;
            idUser = (int)qLTH.tbl_User[tscb_User.SelectedIndex][qLTH.tbl_User.idColumn];

            tbl_QuyenTableAdapter quyenAdap = new tbl_QuyenTableAdapter();
            quyenAdap.Connection.ConnectionString = PublicLib.getStrConn();
            quyenAdap.FillByNguoiDung(qLTH.tbl_Quyen, idUser);

            for (int i = 0; i < qLTH.sys_Quyen.Rows.Count; i++)
            {
                int idQuyen = (int)qLTH.sys_Quyen[i][qLTH.sys_Quyen.idColumn];
                int quyen = 0;
                DataRow[] tmp = qLTH.tbl_Quyen.Select(qLTH.tbl_Quyen.idQuyenColumn.ColumnName + "=" + idQuyen);
                if (tmp.Length > 0)
                    quyen = (int)tmp[0][qLTH.tbl_Quyen.QuyenColumn];

                for (int j = 1; j < data.Columns.Count; j++)
                {
                    data.Rows[i][j] = ((quyen & (1 << (j - 1))) > 0);
                }
            }

            wasSave = true;
        }

        private void refreshData()
        {
            loadComboBox();
            checkUserPower();
            //fillData();
        }

        private void bt_ThemMoi_Click(object sender, EventArgs e)
        {
            //dg_DanhSach.Rows[dg_DanhSach.Rows.Count - 1].Cells[tenDataGridViewTextBoxColumn.Name].Selected = true;
            dg_DanhSach.BeginEdit(true);
        }

        private void dg_DanhSach_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            wasSave = false;
        }

        private void dg_DanhSach_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            for (int i = 0; i < dg_DanhSach.RowCount; i++)
            {
                dg_DanhSach.Rows[i].Cells[cl_STT.Name].Value = (i + 1).ToString();
                dg_DanhSach.Rows[i].DefaultCellStyle.BackColor = (i % 2 == 1) ? PConst.COLOR_BACK_1 : PConst.COLOR_BACK_DEF;
            } 
        }

        private void bt_Xoa_Click(object sender, EventArgs e)
        {
            if (dg_DanhSach.SelectedRows.Count <= 0)
                return;
            //deleteByID(dg_DanhSach.SelectedRows[0].Cells[idDataGridViewTextBoxColumn.Name].Value.ToString());
        }

        private void deleteByID(String _id)
        {
            try
            {
                PublicLib.updateField(qLTH.tbl_DanhGia.TableName,
                                        qLTH.tbl_DanhGia.idColumn.ColumnName,
                                        _id,
                                        qLTH.tbl_DanhGia.flagColumn.ColumnName,
                                        PConst.FLAG_DELETE.ToString());
                refreshData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(MSG.MSG_ERROR_INSERT_DB + " " + ex.Message);
            }
        }

        private void tblDanhGiaBindingSource_CurrentItemChanged(object sender, EventArgs e)
        {
            if ((DataRowView)((BindingSource)sender).Current == null)
                return;
            DataRow ThisDataRow = ((DataRowView)((BindingSource)sender).Current).Row;
            if (ThisDataRow.RowState == DataRowState.Modified ||
                ThisDataRow.RowState == DataRowState.Added)
            {
                //tbl_DanhGiaTableAdapter.Update(ThisDataRow);
            }
        }

        private void QLDanhGia_Resize(object sender, EventArgs e)
        {
            dg_DanhSach.Height = stt_bottom.Top - dg_DanhSach.Top - 2;
            dg_DanhSach.Width = this.Width - 5;
        }

        private void tsb_Luu_Click(object sender, EventArgs e)
        {
            dg_DanhSach.EndEdit();
            saveData();           
        }

        private void saveData()
        {
            //if (tscb_User.SelectedIndex == -1) return;
            //int idUser = (int)qLTH.tbl_User[tscb_User.SelectedIndex][qLTH.tbl_User.idColumn];

            tbl_QuyenTableAdapter quyenAdap = new tbl_QuyenTableAdapter();
            quyenAdap.Connection.ConnectionString = PublicLib.getStrConn();
            quyenAdap.FillByNguoiDung(qLTH.tbl_Quyen, idUser);

            for (int i = 0; i < qLTH.sys_Quyen.Rows.Count; i++)
            {
                int idQuyen = (int)qLTH.sys_Quyen[i][qLTH.sys_Quyen.idColumn];
                int quyen = 0;

                for (int j = 1; j < data.Columns.Count; j++)
                    if ((data.Rows[i][j] != DBNull.Value) && (Boolean)data.Rows[i][j])
                    {
                        quyen = (quyen | (1 << (j - 1)));
                    }

                DataRow[] tmp = qLTH.tbl_Quyen.Select(qLTH.tbl_Quyen.idQuyenColumn.ColumnName + "=" + idQuyen);
                if (tmp.Length > 0)
                    tmp[0][qLTH.tbl_Quyen.QuyenColumn] = quyen;
                else
                {
                    DataRow nRow = qLTH.tbl_Quyen.NewRow();

                    nRow[qLTH.tbl_Quyen.idQuyenColumn] = idQuyen;
                    nRow[qLTH.tbl_Quyen.idNguoiDungColumn] = idUser;
                    nRow[qLTH.tbl_Quyen.QuyenColumn] = quyen;

                    qLTH.tbl_Quyen.Rows.Add(nRow);
                }

            }

            quyenAdap.Update(qLTH.tbl_Quyen);
            // load lai quyen
            PublicLib.loadUserPower(PublicLib.CURR_USER);
            wasSave = true;
        }

        private void tscb_User_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!wasSave)
            {
                if (MessageBox.Show(MSG.MSG_SAVE, "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    saveData();
                wasSave = true;
            }

            fillData();
        }

        private void PhanQuyen_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!wasSave)
                if (MessageBox.Show(MSG.MSG_SAVE, "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    saveData();
        }

        private void tsb_In_Click(object sender, EventArgs e)
        {
            PrintDataGrid.PrintDGV print = new PrintDataGrid.PrintDGV();
            print.Print_DataGridView(dg_DanhSach);
        }
    }
}
